package com.fly.core.config;

import java.lang.reflect.Method;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.fly.common.util.Constant;
import com.fly.core.entity.JsonResult;

import lombok.extern.slf4j.Slf4j;

/**
 * 应答body日志
 * 
 * @author jack
 */
@Slf4j
@ControllerAdvice
public class LogRespBodyAdvice implements ResponseBodyAdvice<JsonResult<?>>
{
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass)
    {
        Method method = methodParameter.getMethod();
        return null != method && method.getReturnType().isAssignableFrom(JsonResult.class);
    }
    
    @Override
    public JsonResult<?> beforeBodyWrite(JsonResult<?> r, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse)
    {
        try
        {
            String text = Constant.OBJECTMAPPER.writeValueAsString(r);
            text = text.length() > 1000 ? text.substring(0, 999) + "..." : text;
            log.info("BODY<<< {}", text);
        }
        catch (Exception e)
        {
            // do nothing
        }
        return r;
    }
    
}
